package com.liaoyin.travel.service.report;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.view.ApiExternal.ApiExternalUser;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.business.util.TaskUtil;
import com.liaoyin.travel.constant.CommonConstant;
import com.liaoyin.travel.dao.report.EventReportMapper;
import com.liaoyin.travel.dao.report.EventUserMapper;
import com.liaoyin.travel.entity.BackUser;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.report.EventReport;
import com.liaoyin.travel.entity.report.EventUser;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.back.BackUserService;
import com.liaoyin.travel.service.external.ApiExternalService;
import com.liaoyin.travel.util.FileUploadUtil;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：事件上报
 * @日期：Created in 2018/6/20 14:55
 */
@Service
public class EventReportService extends BaseService<EventReportMapper, EventReport> {

    /**
     * 服务器目录
     */
    @Value("${gate.file.realPath}")
    private String realPath;

	@Autowired
	private UsersService usersService;
	@Autowired
	private EventUserService eventUserService;
	@Autowired
	private BackUserService backUserService;
	@Autowired
	private ApiExternalService apiExternalService;
	@Resource
    private EventUserMapper eventUserMapper;
	/****
	 * 
	     * @方法名：insertEventReport
	     * @描述： 新增事件上报
	     * @作者： lijing
	     * @日期： 2019年7月24日
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public void insertEventReport(EventReport eventReport) {
		System.err.println("eventReport="+eventReport);
		//获取登录用户信息
		UserInfo activeUser = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));
		/** 景区id */
		String scenicId = activeUser.getScenicId();
		eventReport.setScenicId(scenicId);
		String id = UUIDUtil.getUUID();
		eventReport.setUserId(activeUser.getId());
		eventReport.setCreatTime(new Date());
		eventReport.setId(id);
		eventReport.setIsDelete((short)0);
		eventReport.setEventProgress((short) 1);
		if(eventReport.getAudioFileUploadList()!=null && eventReport.getAudioFileUploadList().size() >0) {
			eventReport.setEventAutoId(FileUploadUtil.saveFileUploadList(eventReport.getAudioFileUploadList(),""));
		}
		if(eventReport.getPicFileUploadList()!=null && eventReport.getPicFileUploadList().size() >0) {
			eventReport.setEventPicId(FileUploadUtil.saveFileUploadList(eventReport.getPicFileUploadList(), ""));
		}
		if (eventReport.getVideoFileUploadList() != null && eventReport.getVideoFileUploadList().size() > 0){
			eventReport.setEventVideoId(FileUploadUtil.saveFileUploadList(eventReport.getVideoFileUploadList(),""));
		}
		int k = this.mapper.insertSelective(eventReport);
		if(k >0) {
			//查询上级管理人员
			if(activeUser.getAssumeOffice()!=null && activeUser.getAssumeOffice().intValue()==2) {
				//员工，查询上级经理
				List<UserTeam> userteamList = activeUser.getUserTeamList();
				if(userteamList==null || userteamList.size() == 0) {
		        	throw new BusinessException("team.is.null");
		        }
		        StringBuffer teamId = new StringBuffer();
		        for(UserTeam u:userteamList) {
		        	teamId.append(u.getTeamId()+",");
		        }
				List<String> list = this.usersService.selectUsersIdListByManager(teamId.toString());
				if(list !=null && list.size() >0) {
					this.eventUserService.insertEventUser(list, id,1);
				}
				//推送至管理员处
			}else if(activeUser.getAssumeOffice()!=null && activeUser.getAssumeOffice().intValue()==1){
				//上级经理   上报到超级管理员处
				List<BackUser> backUsers = this.backUserService.selectBackUserList(null, null, "1", null, "1");
				List<String> strings = new ArrayList<>();
				if (null != backUsers && backUsers.size() > 0){
					for (BackUser backUser : backUsers) {
						strings.add(backUser.getId());
					}
					this.eventUserService.insertEventUser(strings,id,2);
				}
			}
		}
		/** 20200422 沙陀确认需求，报警不发任务*/
		/**如果是一键报警*/
		/*if (eventReport.getEventType() == 2){
			ApiExternalUser apiExternalUser = this.apiExternalService.issueWarningTaskNew("有报警事件发生，立即前往处理", eventReport.getEnvetContext(), eventReport.getEventLat(), eventReport.getEventLog());
			String taskId = "";
			if (null != apiExternalUser){
				taskId = apiExternalUser.getTaskId();
			}else {
				throw new BusinessException("no.idle.users");
			}
			if (null != taskId && !"".equals(taskId)) {
				tempTaskMap.put(taskId+"-event", id);
			}
		}*/
	}

	/**
	　* @description: TODO 查询事件列表
	　* @param [num, size, eventType, queryType]
	　* @return java.util.List<com.liaoyin.travel.entity.report.EventReport>
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/6 10:18
	　*/
	public List<EventReport> selectEventList (Integer num,Integer size,Integer eventType,Integer queryType,String eventTime){
		PageHelper.startPage(num, size);
		UserInfo currentUserInfo = PartyUtil.getCurrentUserInfo();
		if(currentUserInfo == null) {
			throw new BusinessException("not.login");
		}
		String userId=currentUserInfo.getId();
		//查询所有的事件
		if(VariableConstants.STRING_CONSTANT_1.equals(queryType)) {
			//如果担任了【项目经理】的职务
			if(currentUserInfo.getAssumeOffice()!=null && currentUserInfo.getAssumeOffice().intValue()==1) {
				queryType = Integer.valueOf(VariableConstants.STRING_CONSTANT_1);
			}else {
				queryType = Integer.valueOf(VariableConstants.STRING_CONSTANT_2);
			}
		}else {
			queryType=null;
		}
		List<EventReport> eventReports = this.mapper.selectEventList(eventType, queryType,userId,eventTime);
		if(eventReports!=null && eventReports.size() >0) {
			Users users = null;
			for (EventReport report : eventReports) {
				/*String s = this.usersService.selectUserById(report.getUserId());
				if(s !=null &&!"".equals(s)) {
					String[] split = s.split(",");
					report.setUserNikeName(split[0]);
				}*/
				users = this.usersService.selectUsersById(report.getUserId());
				if (null == users){
					continue;
				}
				if(null != users.getHeadPicId()) {
					report.setUserPicPath(users.getHeadUrl());
				}
				if (null != users.getNickName()){
					report.setUserNikeName(users.getNickName());
				}
				users=null;
			}
		}
		return eventReports;
	}

	/**
	 * @方法名：selectEventListByCondition
	 * @描述： 按条件查询事件列表
	 * @作者：wxy
	 * @日期： Created in 2019/11/12 17:19
	 */
	public PageInfo<EventReport> selectEventListByCondition(Integer num, Integer size, Integer eventType, String eventTime, String startTime, String endTime, String reportPersonIds, Integer eventProgress, Integer queryType) {
		PageHelper.startPage(num, size);
		UserInfo currentUserInfo = PartyUtil.getCurrentUserInfo();
		if(currentUserInfo == null) {
			throw new BusinessException("not.login");
		}
		String userId=currentUserInfo.getId();

		/** 景区id */
		String scenicId = currentUserInfo.getScenicId();

		//结束查询时间必须多一天,才能查询到包括结束时间当天的
		if(endTime!=null && endTime.indexOf("-")!=-1){
			endTime = TaskUtil.strGetTomorrow(endTime);
		}
		//查询所有的
		if(VariableConstants.STRING_CONSTANT_1.equals(queryType)) {
			//如果担任了【项目经理】的职务
			if(currentUserInfo.getAssumeOffice()!=null && currentUserInfo.getAssumeOffice().intValue()==1) {
				queryType = Integer.valueOf(VariableConstants.STRING_CONSTANT_1);
			}else {
				queryType = Integer.valueOf(VariableConstants.STRING_CONSTANT_2);
			}
		}
		List<String> reportPersonList = new ArrayList<>();
		System.err.println("queryType="+queryType);
		if(reportPersonIds!=null && !"".equals(reportPersonIds)){
			String[] reportPersonId = reportPersonIds.split(",");
			 reportPersonList = Arrays.asList(reportPersonId);
		}

		List<EventReport> eventReports = this.mapper.selectEventListByCondition(eventType,queryType,userId,eventTime,startTime,endTime,reportPersonList,eventProgress,scenicId);
		if(eventReports!=null && eventReports.size() >0) {
			Users users = null;
			for (EventReport report : eventReports) {
				/*String s = this.usersService.selectUserById(report.getUserId());
				if(s !=null &&!"".equals(s)) {
					String[] split = s.split(",");
					report.setUserNikeName(split[0]);
				}*/
				users = this.usersService.selectUsersById(report.getUserId());
				if (null == users){
					continue;
				}
				if(null != users.getHeadPicId()) {
					report.setUserPicPath(users.getHeadUrl());
				}
				if (null != users.getNickName()){
					report.setUserNikeName(users.getNickName());
				}
				users=null;
			}
		}
		PageInfo<EventReport> pageInfo = new PageInfo<>(eventReports);
		return pageInfo;
	}

    /**
    　* @description: TODO 查询事件详情根据事件id
    　* @param [eventId]
    　* @return com.liaoyin.travel.entity.report.EventReport
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/6 10:33
    　*/
	public EventReport selectEventDetail(String eventId){
        EventReport eventReport = this.mapper.selectByPrimaryKey(eventId);
        Example example = new Example(EventUser.class);
        example.and().andEqualTo("eventId",eventId);
        eventReport.setEventUsers(eventUserMapper.selectByExample(example));
        eventReport.setUserNikeName(this.usersService.selectById(eventReport.getUserId()).getNickName());
        if (null != eventReport.getEventPicId()) {
            List<FileUpload> picFileUploadList = FileUploadUtil.getFileUploadList(eventReport.getEventPicId());
            if (picFileUploadList != null && picFileUploadList.size() > 0) {
                eventReport.setPicFileUploadList(picFileUploadList);
                List<String> picList = new ArrayList<String>();
                picFileUploadList.stream().forEach((f) -> {
                    picList.add(CommonConstant.FILE_SERVER + f.getFilePath());
                });
                eventReport.setPicList(picList);
                picFileUploadList = null;
            }
        }
        if (null != eventReport.getEventAutoId()) {
            List<FileUpload> audioFileUploadList = FileUploadUtil.getFileUploadList(eventReport.getEventAutoId());
            if (audioFileUploadList != null && audioFileUploadList.size() > 0) {
                eventReport.setAudioFileUploadList(audioFileUploadList);
                List<String> audioList = new ArrayList<String>();
                audioFileUploadList.stream().forEach((f) -> {
                    audioList.add(f.getFilePath());
                });
                eventReport.setAudioList(audioList);
                audioFileUploadList = null;
            }
        }
		if (null != eventReport.getEventVideoId()) {
			List<FileUpload> videoFileUploadList = FileUploadUtil.getFileUploadList(eventReport.getEventVideoId());
			if (videoFileUploadList != null && videoFileUploadList.size() > 0) {
				eventReport.setAudioFileUploadList(videoFileUploadList);
				List<String> videoList = new ArrayList<String>();
				videoFileUploadList.stream().forEach((f) -> {
					videoList.add(CommonConstant.FILE_SERVER + f.getFilePath());
				});
				eventReport.setVideoList(videoList);
				videoFileUploadList = null;
			}
		}
        return eventReport;
    }


    /**
    　* @description: TODO 根据事件ID更新事件状态（进度）
    　* @param [eventProgress, eventId]
    　* @return int
    　* @throws
    　* @author privatePanda777@163.com
    　* @date 2019/8/6 12:46
    　*/
    public int updateEventProgress(Integer eventProgress,String eventId){
        EventReport eventReport = new EventReport();
        eventReport.setId(eventId);
        eventReport.setEventProgress(eventProgress.shortValue());
        int i = this.mapper.updateByPrimaryKeySelective(eventReport);
        return i;
    }

    /**
     * @方法名：selectEventListByReportPerson
     * @描述： 根据上报人id等条件查询事件列表
     * @作者： why
     * @日期： Created in 2019/11/5 10:33
     */
	public PageInfo<EventReport> selectEventListByReportPerson(Integer num, Integer size, Integer eventType, String userId, String eventTime) {
		UserInfo currentUserInfo = PartyUtil.getCurrentUserInfo();
		if(currentUserInfo == null) {
			throw new BusinessException("not.login");
		}
		//如果没有传usreId，那就是默认查当前登录用户的id
		if(userId==null){
			userId = currentUserInfo.getId();
		}
		/** 景区id */
		String scenicId = currentUserInfo.getScenicId();
		PageHelper.startPage(num, size);
		List<EventReport> list = this.mapper.selectEventListByReportPerson(eventType,userId,eventTime,scenicId);
		if(list!=null && list.size() >0) {
			list.forEach(report->{
				Users users = this.usersService.selectUsersById(report.getUserId());
				if (users != null){
					if(null != users.getHeadPicId()) {
						report.setUserPicPath(users.getHeadUrl());
					}
					if (null != users.getNickName()){
						report.setUserNikeName(users.getNickName());
					}
				}
			});
		}
		PageInfo<EventReport> p = new PageInfo<>(list);
		return p;
	}

	/**
	 * @方法名：downAudioFileByPathAndName
	 * @描述： 通过mp3相对路径和文件名下载音频
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2020/4/23 1:02
	 */
    public void downAudioFileByPathAndName(HttpServletResponse response, String filePath,String fileName){
        InputStream in = null;
        try {

            // request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //让浏览器另存为（部分浏览器不支持）
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            File file = new File(realPath+filePath);
            in = new FileInputStream(file);
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = in.read(buffer);
                if (b != -1) {
                    response.getOutputStream().write(buffer, 0, b);//4.写到输出流(out)中
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                response.getOutputStream().flush();
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                System.err.println("关闭文件IOException!");
                e.printStackTrace();
            }

        }
	}


}
